﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindow.Domains;
using UIWindow.Entitys;
using UIWindow.Enums;
using UIWindow.GlobalParameters;
using UIWindow.Helper;
using UIWindow.Services.Context;

namespace UIWindow.Services.Handle
{
    public class Weighing : TaskEventBase<WeighingContext>, Lucifer.ITaskEvent<WeighingContext>
    {
        private ParameterGlobal _parameter;
        private HomePageGlobal _homePage;
        private DeviceGlobal _device;
        private UserGlobal _user;
        public Weighing(ParameterGlobal parameter, HomePageGlobal homePage, DeviceGlobal device, UserGlobal userGlobal)
        {
            _parameter = parameter;
            _homePage = homePage;
            _device = device;
            _user = userGlobal;
        }
        public override Task Handle(WeighingContext context)
        {
            try
            {
                $"条码：[{context.BarCode}] 称重启动".RunLog(MessageLevelType.Info);
                var device = _device.DeviceList.FirstOrDefault(k => k.Types == DeviceType.前称重);
                var plc = _device.DeviceList.FirstOrDefault(t => t.Types == DeviceType.注液机).Comm;
                DateTime dateTime = DateTime.Now;
            DataThis:
                ProductionData.Meta.TableName = $"ProductionData_{dateTime:yyyy}{dateTime.GetQuarterly()}";
                var entity = ProductionData.Find(ProductionData._.BarCode == context.BarCode);
                if (entity == null)
                {
                    if (dateTime.ContrastTime())
                    {
                        dateTime = dateTime.AddDays(-1);
                        goto DataThis;
                    }
                    $"前称重 找不到【{context.BarCode}】条码".RunLog(MessageLevelType.Warning);
                    return base.Handle(context);
                }
                Stopwatch stopwatch = new();
                stopwatch.Restart();
                double? weight = null;
                switch (entity.Stage)
                {
                    case 1:
                        while (stopwatch.ElapsedMilliseconds < _parameter.RunParameter.WeighingTimeout)
                        {
                            weight = device.Comm.ByteCache.ToArray().GetWeighingWeight();
                            if (weight != null)
                            {
                                var model3 = ((double)weight).JudgmentBeforeWeighing(_parameter.WeighingParameter);
                                if (model3.Item1 == NGType.合格) break;
                            }
                            Thread.Sleep(200);
                        }
                        stopwatch.Stop();
                        if (weight == null)
                        {
                            $"条码：[{context.BarCode}] 前称重异常：未获取到正确数值".RunLog(MessageLevelType.Warning);
                            _homePage.HomeProperty.NGTotal += 1;
                            entity.JudgementResultAfterWeighing = NGType.称重NG;
                            entity.Update();
                            return base.Handle(context);
                        }
                        entity.FrontWeighTime = dateTime;
                        entity.Preweight = (double)weight;
                        if (_parameter.RunParameter.ProductType == "二次注液")
                        {
                            DateTime dateTime1 = DateTime.Now;
                        DataThis1:
                            using (var mysql = ProductionData.Meta.CreateSplit("MySqlOne", $"ProductionData_{dateTime1:yyyy}{dateTime1.GetQuarterly()}"))
                            {
                                var entity1 = ProductionData.Find(ProductionData._.BarCode == context.BarCode);
                                if (entity1 == null)
                                {
                                    if (dateTime1.ContrastTime())
                                    {
                                        dateTime1 = dateTime1.AddMonths(-1);
                                        goto DataThis1;
                                    }
                                    $"条码：[{context.BarCode}] 一注 找不到【{context.BarCode}】条码".RunLog(MessageLevelType.Warning);
                                }
                                else
                                {
                                    entity.OneAfterweight = entity1.Afterweight;
                                    entity.OnePreweight = entity1.Preweight;
                                    entity.LossAfterFormation = Math.Round(entity1.Afterweight - (double)weight, 2, MidpointRounding.AwayFromZero);
                                    entity.FluidRateAims = Math.Round(_parameter.WeighingParameter.InjectionVolume - ((double)weight - entity1.Preweight), 2, MidpointRounding.AwayFromZero);
                                    if (entity.FluidRateAims > 0)
                                    {
                                        byte[] bytefloat = BitConverter.GetBytes((float)entity.FluidRateAims);
                                        if (plc.Write(new Models.S7NET.S7ParamModel() { Address = context.AddressInjection, Value = new byte[] { bytefloat[3], bytefloat[2], bytefloat[1], bytefloat[0] } }))
                                        {
                                            $"条码：{entity.BarCode} 注液量：{entity.FluidRateAims}克写入成功".RunLog(MessageLevelType.Info);
                                        }
                                        else
                                        {
                                            $"条码：{entity.BarCode} 注液量：{entity.FluidRateAims}克写入失败".RunLog(MessageLevelType.Warning);
                                        }
                                    }
                                    else
                                    {
                                        $"条码：{entity.BarCode} 注液量小于等于0克，不及于注液!!!".RunLog(MessageLevelType.Warning);
                                    }
                                }
                            }
                        }
                        if (_parameter.DecideParameter.EnableBeforeInjection)
                        {
                            var model2 = ((double)weight).JudgmentBeforeWeighing(_parameter.WeighingParameter);
                            entity.JudgementResultForeweigh = model2.Item1;
                        }
                        entity.Update();
                        var aftermodel1 = _homePage.AfterWeighingList.FirstOrDefault(x => x.BarCode == context.BarCode);
                        if (aftermodel1 == null) _homePage.AfterWeighingListAdd(entity);
                        else
                        {
                            aftermodel1.Preweight = entity.Preweight;
                            aftermodel1.FluidRateAims = entity.FluidRateAims;
                        }
                        _homePage.BeforeWeighingListAdd(entity);
                        break;
                    case 2:
                        while (stopwatch.ElapsedMilliseconds < _parameter.RunParameter.WeighingTimeout)
                        {
                            weight = device.Comm.ByteCache.ToArray().GetWeighingWeight();
                            if (weight != null)
                            {
                                if (_parameter.RunParameter.ProductType == "二次注液")
                                {
                                    if (((double)weight).JudgmentAfterWeighing(Math.Round((double)(weight - entity.OnePreweight), 2, MidpointRounding.AwayFromZero), _parameter.WeighingParameter).Item1 == NGType.合格) { break; }
                                }
                                else
                                {
                                    if (((double)weight).JudgmentAfterWeighing(Math.Round((double)(weight - entity.Preweight), 2, MidpointRounding.AwayFromZero), _parameter.WeighingParameter).Item1 == NGType.合格) { break; }
                                }
                            }
                            Thread.Sleep(200);
                        }
                        stopwatch.Stop();
                        if (weight == null)
                        {
                            $"条码：[{context.BarCode}] 后称重异常：未获取到正确数值".RunLog(MessageLevelType.Warning);
                            _homePage.HomeProperty.NGTotal += 1;
                            entity.JudgementResultAfterWeighing = NGType.称重NG;
                            entity.Update();
                            return base.Handle(context);
                        }
                        entity.BackWeighTime = dateTime;
                        entity.Afterweight = (double)weight;
                        entity.FluidRate = Math.Round(entity.Afterweight - entity.Preweight, 2, MidpointRounding.AwayFromZero);
                        if (_parameter.RunParameter.ProductType == "二次注液")
                        {
                            DateTime dateTime1 = DateTime.Now;
                        DataThis1:
                            using (var mysql = ProductionData.Meta.CreateSplit("MySqlOne", $"ProductionData_{dateTime1:yyyy}{dateTime1.GetQuarterly()}"))
                            {
                                var entity1 = ProductionData.Find(ProductionData._.BarCode == context.BarCode);
                                if (entity1 == null)
                                {
                                    if (dateTime1.ContrastTime())
                                    {
                                        dateTime1 = dateTime1.AddDays(-1);
                                        goto DataThis1;
                                    }
                                    $"条码：[{context.BarCode}] 一注 找不到【{context.BarCode}】条码".RunLog(MessageLevelType.Warning);
                                }
                                else
                                {
                                    entity.Ownership = Math.Round(entity.Afterweight - entity1.Preweight, 2, MidpointRounding.AwayFromZero);
                                }
                            }
                            var model = entity.Afterweight.JudgmentAfterWeighing(entity.Ownership, _parameter.WeighingParameter);
                            entity.JudgementResultAfterWeighing = model.Item1;
                            entity.DeviationValue = model.Item2;
                        }
                        else
                        {
                            var model = entity.Afterweight.JudgmentAfterWeighing(entity.FluidRate, _parameter.WeighingParameter);
                            entity.JudgementResultAfterWeighing = model.Item1;
                            entity.DeviationValue = model.Item2;
                        }
                        $"注液结果：{entity.JudgementResultAfterWeighing}".MessageDialogsUI(MessageLevelType.Warning);
                        entity.Cycles = context.Cycles;
                        entity.CupNumber = context.CupNumber;
                        entity.NegativePressure = context.NegativePressure;
                        entity.PositivePressure = context.PositivePressure;
                        entity.StationNo = $"{Encoding.ASCII.GetString(new byte[] { (byte)(64 + context.StationNo) })}站";
                        entity.VacuumDegreeAfterReturningHelium = context.VacuumDegreeAfterReturningHelium;
                        entity.VacuumBeforeFilling = context.VacuumBeforeFilling;
                        entity.VacuumBeforeReturningHelium = context.VacuumBeforeReturningHelium;
                        entity.VacuumBeforeFillingSetting = context.VacuumBeforeFillingSetting;
                        entity.PositivePressureSetting = context.PositivePressureSetting;
                        entity.NegativePressureSetting = context.NegativePressureSetting;
                        entity.TimePositivePressure = context.TimePositivePressure;
                        entity.TimePositivePressureSetting = context.TimePositivePressureSetting;
                        entity.TimeNegativePressure = context.TimeNegativePressure;
                        entity.TimeNegativePressureSetting = context.TimeNegativePressureSetting;

                        entity.Update();
                        var aftermodel = _homePage.AfterWeighingList.FirstOrDefault(x => x.BarCode == context.BarCode);
                        if (aftermodel == null) _homePage.AfterWeighingListAdd(entity);
                        else
                        {
                            aftermodel.Afterweight = entity.Afterweight;
                            aftermodel.FluidRate = entity.FluidRate;
                            aftermodel.Cycles = context.Cycles;
                            aftermodel.CupNumber = entity.CupNumber;
                            aftermodel.NegativePressure = context.NegativePressure;
                            aftermodel.PositivePressure = context.PositivePressure;
                            aftermodel.StationNo = entity.StationNo;
                            aftermodel.VacuumDegreeAfterReturningHelium = context.VacuumDegreeAfterReturningHelium;
                            aftermodel.VacuumBeforeFilling = context.VacuumBeforeFilling;
                            aftermodel.VacuumBeforeReturningHelium = context.VacuumBeforeReturningHelium;
                            aftermodel.JudgementResultAfterWeighing = entity.JudgementResultAfterWeighing;
                            aftermodel.BackWeighTime = dateTime;
                        }

                        _homePage.HomeProperty.Outbound += 1;
                        if (entity.JudgementResultAfterWeighing != NGType.合格)
                        {
                            _homePage.HomeProperty.NGTotal += 1;
                            _homePage.HomeProperty.InjectionNG += 1;
                        }
                        _homePage.HomeProperty.OKTotal = _homePage.HomeProperty.Outbound - _homePage.HomeProperty.NGTotal;
                        _homePage.HomeProperty.Yield = _homePage.HomeProperty.OKTotal / (double)_homePage.HomeProperty.Outbound;
                        break;
                    case 3:
                        while (stopwatch.ElapsedMilliseconds < _parameter.RunParameter.WeighingTimeout)
                        {
                            weight = device.Comm.ByteCache.ToArray().GetWeighingWeight();
                            if (weight != null)
                            {
                                var model3 = ((double)weight).JudgmentAfterWeighing(Math.Round((double)(weight - entity.Preweight), 2, MidpointRounding.AwayFromZero), _parameter.WeighingParameter);
                                if (model3.Item1 == NGType.合格) break;
                            }
                            Thread.Sleep(200);
                        }
                        stopwatch.Stop();
                        if (weight == null)
                        {
                            $"条码：[{context.BarCode}] 补液称重异常：未获取到正确数值".RunLog(MessageLevelType.Warning);
                            _homePage.HomeProperty.NGTotal += 1;
                            entity.JudgementResultAfterWeighing = UIWindow.Enums.NGType.称重NG;
                            entity.Update();
                            return base.Handle(context);
                        }
                        var model1 = entity.Afterweight.JudgmentAfterWeighing(entity.FluidRate, _parameter.WeighingParameter);
                        entity.JudgementResultAfterWeighing = model1.Item1;
                        entity.RehydrationWeighing = (double)weight;
                        entity.Update();
                        entity.FluidInjectionVolume = Math.Round(entity.RehydrationWeighing - entity.Afterweight, 2, MidpointRounding.AwayFromZero);
                        var aftermodel2 = _homePage.AfterWeighingList.FirstOrDefault(x => x.BarCode == context.BarCode);
                        if (aftermodel2 == null) _homePage.AfterWeighingListAdd(entity);
                        else aftermodel2.RehydrationWeighing = entity.RehydrationWeighing;
                        break;
                    default:
                        break;
                }
                if (_parameter.DecideParameter.EnableMES && entity.Stage > 1)
                {
                    //Models.Testdatap[] testdata = null;
                    List<Models.Testdatap> testdata = new List<Models.Testdatap>();
                    if (_parameter.RunParameter.ProductType == "二次注液")
                    {
                
                        testdata = new List<Models.Testdatap>
                        {
                             new Models.Testdatap()
                            {
                                ItemCode = "工序名",
                                Value = $"{_parameter.RunParameter.GroupCode}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "班次",
                                Value = $"{GetTimeSpan(DateTime.Now)}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "制令单",
                                Value = $"{_parameter.RunParameter.MoNumber}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "组别",
                                Value =$"{_parameter.RunParameter.GroupName}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电芯条码",
                                Value = entity.BarCode
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "设备编号",
                                Value =$"{_parameter.RunParameter.EquipNum}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "注液工位",
                                Value = entity.StationNo.ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "进站时间",
                                Value = $"{entity.FrontScanTime:yyyy-MM-dd HH:mm:ss}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "出站时间",
                                Value = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电解液料号",
                                Value = entity.ElectrolyteMaterialNumber
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电解液批次号",
                                Value = entity.BatchElectrolyte
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电解液氢氟酸含量",
                                Value = entity.HydrofluoricAcidContent.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电解液含水量",
                                Value = entity.ElectrolyteWaterContent.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注电芯注液前重量上限值（g）",
                                Value =(_parameter.WeighingParameter.WeighBeforeFilling + _parameter.WeighingParameter.FluctuationWeighBeforeFilling).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注电芯注液前重量下限值（g）",
                                 Value =(_parameter.WeighingParameter.WeighBeforeFilling - _parameter.WeighingParameter.FluctuationWeighBeforeFilling).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注电芯注液前重量实际值（g）",
                                Value = entity.Preweight.ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注电芯注液后重量上限值（g）",
                                Value =(_parameter.WeighingParameter.WeighAfterFilling + _parameter.WeighingParameter.FluctuationWeighAfterFilling).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注电芯注液后重量下限值（g）",
                                Value =(_parameter.WeighingParameter.WeighAfterFilling - _parameter.WeighingParameter.FluctuationWeighAfterFilling).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注电芯注液后重量实际值（g）",
                                Value = entity.Afterweight.ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注注液量上限值（g）",
                                Value =(_parameter.WeighingParameter.InjectionVolume + _parameter.WeighingParameter.FluctuationInjectionVolume).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注注液量下限值（g）",
                                Value = (_parameter.WeighingParameter.InjectionVolume + _parameter.WeighingParameter.FluctuationInjectionVolume).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "二注注液量实际值（g）",
                                Value = entity.FluidRate.ToString()
                            },
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "重量校准上限值（g）",
                            //    Value = entity.WeightCalibrationUpperLimit
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "重量校准下限值（g）",
                            //    Value = entity.WeightCalibrationLowerLimit
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "重量校准实际值（g）",
                            //    Value = entity.WeightCalibrationActual
                            //},
                        //    new Models.Testdatap()
                        //    {
                        //        ItemCode = "液矢量上限值（g）",
                        //        Value = entity.LiquidVectorUpperLimit
                        //    },
                        //    new Models.Testdatap()
                        //    {
                        //        ItemCode = "液矢量下限值（g）",
                        //        Value = entity.LiquidVectorLowerLimit
                        //    },
                            new Models.Testdatap()
                            {
                                ItemCode = "液矢量实际值（g）",
                              Value = entity.LossAfterFormation.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "保液量设定值（g）",
                                Value =_parameter.WeighingParameter.WeighAfterFilling.ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "保液量上限值（g）",
                                Value =(_parameter.WeighingParameter.WeighAfterFilling + _parameter.WeighingParameter.FluctuationWeighAfterFilling).ToString()
                            },
                         new Models.Testdatap()
                        {
                            ItemCode = "保液量下限值（g）",
                            Value =(_parameter.WeighingParameter.WeighAfterFilling - _parameter.WeighingParameter.FluctuationWeighAfterFilling).ToString()
                        },
                          new Models.Testdatap()
                        {
                            ItemCode = "保液量实际值（g）",
                            Value = entity.Ownership.ToString("F2"),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注注液前真空度设定值（kPa）",
                            Value = context.VacuumBeforeFillingSetting.ToString("F2"),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注注液前真空度实际值（kPa）",
                            Value = entity.VacuumBeforeFilling.ToString("F2"),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注注液正压设定值（kPa）",
                            Value = context.PositivePressureSetting.ToString("F2"),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注注液正压实际值（kPa）",
                              Value = entity.PositivePressure.ToString("F2"),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注正压时间设定值（S）",
                            Value = context.TimePositivePressureSetting.ToString(),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注正压时间实际值（S）",
                            Value = context.TimePositivePressure.ToString(),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注注液负压设定值（kPa）",
                              Value = context.NegativePressureSetting.ToString("F2"),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注注液负压实际值（kPa）",
                              Value = entity.NegativePressure.ToString("F2"),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注负压时间设定值（S）",
                            Value = context.TimeNegativePressureSetting.ToString(),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注负压时间实际值（S）",
                            Value = context.TimeNegativePressure.ToString(),
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "二注循环次数",
                            Value = context.Cycles.ToString()
                        },
                        //new Models.Testdatap()
                        //{
                        //    ItemCode = "返工后称重（g）",
                        //    Value = entity.ReworkWeight
                        //},
                        //new Models.Testdatap()
                        //{
                        //    ItemCode = "返工注液量（g）",
                        //    Value = entity.ReworkLiquidAmount
                        //},
                        //new Models.Testdatap()
                        //{
                        //    ItemCode = "返工时间",
                        //    Value = entity.ReworkTime
                        //},
                        //new Models.Testdatap()
                        //{
                        //    ItemCode = "返工判定",
                        //    Value = entity.ReworkJudgment
                        //},
                        //new Models.Testdatap()
                        //{
                        //    ItemCode = "返工NG详情",
                        //    Value = entity.ReworkNGDetails
                        //},
                        new Models.Testdatap()
                        {
                            ItemCode = "作业员",
                            Value = entity.UserName
                        },
                        new Models.Testdatap()
                        {
                            ItemCode = "NG详情",
                             Value = $"{entity.JudgementResultAfterWeighing}",
                        }
                        };
                    }
                    else
                    {
            


                        testdata = new List<Models.Testdatap>
                        {
                            new Models.Testdatap()
                            {
                                ItemCode = "工序名",
                                Value = $"{_parameter.RunParameter.GroupCode}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "班次",
                                Value = $"{GetTimeSpan(DateTime.Now)}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "制令单",
                                Value = $"{_parameter.RunParameter.MoNumber}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "组别",
                                Value =$"{_parameter.RunParameter.GroupName}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电芯条码",
                                Value = entity.BarCode
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "设备编号",
                                Value =$"{_parameter.RunParameter.EquipNum}",
                            },
                                new Models.Testdatap()
                            {
                                ItemCode = "注液工位",
                                Value = entity.StationNo.ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "进站时间",
                                Value = $"{entity.FrontScanTime:yyyy-MM-dd HH:mm:ss}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "出站时间",
                                Value = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}",
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电解液料号",
                                Value = entity.ElectrolyteMaterialNumber
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电解液批次号",
                                Value = entity.BatchElectrolyte
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电解液氢氟酸含量",
                                Value = entity.HydrofluoricAcidContent.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "电解液含水量",
                                Value = entity.ElectrolyteWaterContent.ToString("F2"),
                            },
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "Hi-pot电阻上限值（MΩ）",
                            //    Value = entity.HiPotResistanceUpperLimit
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "Hi-pot电阻下限值（MΩ）",
                            //    Value = entity.HiPotResistanceLowerLimit
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "Hi-pot电阻实际值（MΩ）",
                            //    Value = entity.HiPotResistanceActual
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "Hi-pot电压设定值（V）",
                            //    Value = entity.HiPotVoltageSetting
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "Hi-pot电压实际值（V）",
                            //    Value = entity.HiPotVoltageActual
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "Hi-pot测试时间设定值（S）",
                            //    Value = entity.HiPotTestTimeSetting
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "Hi-pot测试时间实际值（S）",
                            //    Value = entity.HiPotTestTimeActual
                            //},
                            new Models.Testdatap()
                            {
                                ItemCode = "一注电芯注液前重量上限值（g）",
                               Value =(_parameter.WeighingParameter.WeighBeforeFilling + _parameter.WeighingParameter.FluctuationWeighBeforeFilling).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注电芯注液前重量下限值（g）",
                                Value =(_parameter.WeighingParameter.WeighBeforeFilling - _parameter.WeighingParameter.FluctuationWeighBeforeFilling).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注电芯注液前重量实际值（g）",
                                Value = entity.Preweight.ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注电芯注液后重量上限值（g）",
                                Value =(_parameter.WeighingParameter.WeighAfterFilling + _parameter.WeighingParameter.FluctuationWeighAfterFilling).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注电芯注液后重量下限值（g）",
                                Value =(_parameter.WeighingParameter.WeighAfterFilling - _parameter.WeighingParameter.FluctuationWeighAfterFilling).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注电芯注液后重量实际值（g）",
                                Value = entity.Afterweight.ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液量上限值（g）",
                                 Value =(_parameter.WeighingParameter.InjectionVolume + _parameter.WeighingParameter.FluctuationInjectionVolume).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液量下限值（g）",
                                  Value =(_parameter.WeighingParameter.InjectionVolume - _parameter.WeighingParameter.FluctuationInjectionVolume).ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液量实际值（g）",
                                Value = entity.FluidRate.ToString()
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液前真空度设定值（kPa）",
                                Value = context.VacuumBeforeFillingSetting.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液前真空度实际值（kPa）",
                                Value = entity.VacuumBeforeFilling.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液正压设定值（kPa）",
                                Value =  context.PositivePressureSetting.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液正压实际值（kPa）",
                                Value = entity.PositivePressure.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注单次正压时间设定值",
                                 Value = context.TimePositivePressureSetting.ToString(),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注单次正压时间实际值",
                                 Value = context.TimePositivePressure.ToString(),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液负压设定值（kPa）",
                                Value = context.NegativePressureSetting.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注注液负压实际值（kPa）",
                                Value = entity.NegativePressure.ToString("F2"),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注单次负压时间设定值（S）",
                                Value = context.TimeNegativePressureSetting.ToString(),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注单次负压时间实际值（S）",
                               Value = context.TimeNegativePressure.ToString(),
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "一注循环次数",
                                Value = context.Cycles.ToString()
                            },
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "返工后称重（g）",
                            //    Value = entity.ReworkAfterWeighing
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "返工注液量（g）",
                            //    Value = entity.ReworkInjectionVolume
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "返工时间",
                            //    Value = entity.ReworkTime
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "返工判定",
                            //    Value = entity.ReworkJudgment
                            //},
                            //new Models.Testdatap()
                            //{
                            //    ItemCode = "返工NG详情",
                            //    Value = entity.ReworkNGDetails
                            //},
                            new Models.Testdatap()
                            {
                                ItemCode = "作业员",
                                Value = entity.UserName
                            },
                            new Models.Testdatap()
                            {
                                ItemCode = "NG详情",
                                 Value = $"{entity.JudgementResultAfterWeighing}",
                            }
                        };
                    }
                    #region 参数
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "作业员",
                    //    Value = $"{entity.UserName}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "设备机台号",
                    //    Value = $"{_parameter.RunParameter.EquipNum}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "投入时间",
                    //    Value = $"{entity.FrontScanTime:yyyy-MM-dd HH:mm:ss}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "产出时间",
                    //    Value = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "电芯条码",
                    //    Value = $"{entity.BarCode}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "工序名",
                    //    Value = $"{_parameter.RunParameter.GroupCode}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "班次",
                    //    Value = $"{GetTimeSpan(DateTime.Now)}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "综合判定结果",
                    //    Value = $"{entity.JudgementResultAfterWeighing == NGType.合格}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "NG详情",
                    //    Value = $"{entity.JudgementResultAfterWeighing}",
                    //});
                    //testdata.Add(new Models.Testdatap()
                    //{
                    //    ItemCode = "package号",
                    //    Value = $"{_parameter.RunParameter.MoNumber}",
                    //});
                    #endregion
                    MyMesHelper.TestDataGroupInfo(new Models.ProcessParametersModel()
                    {
                        GroupCode = entity.GroupCode,
                        GroupName = entity.GroupName,
                        OperatorID = _user.LoginUser.Name,
                        ProductSn = context.BarCode,
                        TimeStamp = entity.FrontScanTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        MachineID = _parameter.RunParameter.EquipNum,
                        MoNumber = _parameter.RunParameter.MoNumber,
                        TestResult = entity.JudgementResultAfterWeighing != NGType.合格 ? "1" : "0",
                        Material = new Models.Materialp[] {
                                    new Models.Materialp(){
                                        MaterialLot = _parameter.RunParameter.BatchElectrolyte,
                                        MaterialNo = _parameter.RunParameter.ElectrolyteMaterialNumber,
                                    }
                                },
                        TestData = testdata.ToArray(),
                    }, _parameter.MESParameter.TestDataGroupInfoNumber);
                    entity.MESOnline = true;
                    entity.Update();
                }
            }
            catch (Exception ex)
            {
                $"称重异常：{ex}".RunLog(MessageLevelType.Warning);
            }
            return base.Handle(context);
        }

        protected string GetTimeSpan(DateTime timeStr)
        {
            //判断当前时间是否在工作时间段内
            string _strWorkingDayAM = "08:30";//工作时间上午08:30
            string _strWorkingDayPM = "18:00";
            TimeSpan dspWorkingDayAM = DateTime.Parse(_strWorkingDayAM).TimeOfDay;
            TimeSpan dspWorkingDayPM = DateTime.Parse(_strWorkingDayPM).TimeOfDay;
            //string time1 = "2017-2-17 8:10:00";
            //DateTime t1 = Convert.ToDateTime(timeStr);
            TimeSpan dspNow = timeStr.TimeOfDay;
            if (dspNow > dspWorkingDayAM && dspNow < dspWorkingDayPM)
            {
                return "早班";
            }
            return "晚班";
        }
    }
}
